<?php

// +----------------------------------------------------------------------
// | Author: 发仔 <i@fazi.me>
// +----------------------------------------------------------------------

namespace app\adminapi\controller;

use think\Db;

class Feiyong extends Base {

    public function index() {
        $orgnId = input('orgnId');
        $start_time = input('start');
        $end_time = input('end');
        $page = input('page', 1);   
        $offset = input('offset', 20);
        if ($start_time > $end_time) {
            return $this->retError('时间输入错误');
        }
        $w['start_date'] = ['between', [$start_time, $end_time]];
        $wxquery = Db::table('p_maintenance_record')->field('car_id,sum(price)as wxp')->where($w)->group('car_id')->fetchSql(true)->select();
        $njquery = Db::table('p_mot_record')->field('car_id,sum(price)as njp')->where($w)->group('car_id')->fetchSql(true)->select();
        $bxquery = Db::table('p_car_insure')->field('car_id,sum(policy_charge)as bxp')->where($w)->group('car_id')->fetchSql(true)->select();
        $yfquery = Db::table('p_refuel_record')->field('car_id,sum(price)as yfp')->where($w)->group('car_id')->fetchSql(true)->select();
        $count = Db::name('car')->where(['car_rental_id' => $orgnId])->count();
        $car = Db::name('car')->alias('a')->join("($wxquery) wxquery", 'wxquery.car_id=a.car_id', 'LEFT')->
                        join("($njquery) njquery", 'njquery.car_id=a.car_id', 'LEFT')->
                        join("($bxquery) bxquery", 'bxquery.car_id=a.car_id', 'LEFT')->
                        join("($yfquery) yfquery", 'yfquery.car_id=a.car_id', 'LEFT')->
                        where(['a.car_rental_id' => $orgnId])->field('a.number,a.car_id,a.car_rental_id,wxp,njp,bxp,yfp,sum(ifnull(wxp,0)+ifnull(bxp,0)+ifnull(njp,0)+ifnull(yfp,0)) as zonghe')->page($page, $offset)->group('car_id')->select();
        if ($car) {
            $data = [
                'status' => 1,
                'info' => 'ok',
                'count' => $count,
                'vehicleCostsList' => $car,
            ];
            return $this->retSucc($data);
        } else {
            return $this->retError([
                        'status' => 0,
                        'info' => '参数错误',
                        'count' => $count
            ]);
        }
    }

    
}
